package com.xiaojf.xfile.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.xiaojf.xfile.configure.props.LocalFileStorageProperties;
import com.xiaojf.xfile.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

/**
 * 本地磁盘文件服务
 *
 * @author Ade.Xiao 2021/4/10 10:32
 */
public class LocalFileServiceImpl implements FileService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LocalFileServiceImpl.class);
    private LocalFileStorageProperties localFileStorageProperties;

    public LocalFileServiceImpl(LocalFileStorageProperties localFileStorageProperties) {
        this.localFileStorageProperties = localFileStorageProperties;
    }

    @Override
    public String storage(InputStream fileInputStream, String fileSuffix) {
        if (fileInputStream != null) {
            String dict = localFileStorageProperties.getBasePath();
            String fileUri = DateUtil.format(new Date(), localFileStorageProperties.getDateFormat()) + "/" + UUID.fastUUID().toString(true) + "." + StrUtil.blankToDefault(fileSuffix, "");
            File destFile = new File(dict + "/" + fileUri);
            // 保存文件
            FileUtil.writeFromStream(fileInputStream, destFile);
            return fileUri;
        }
        return null;
    }

    @Override
    public File loadFile(String uri) {
        try {
            if (StrUtil.isNotBlank(uri)) {
                String dict = localFileStorageProperties.getBasePath();
                File file = new File(dict + "/" + uri);

                if (file.exists()) {
                    File tmpFile = File.createTempFile("_tmp", "." + FileUtil.getSuffix(uri));
                    FileUtil.copy(file, tmpFile, true);
                    return tmpFile;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }
}
